package com.hippo.javacore.javaiostream.iostream;

import java.io.*;

/**
 * @ClassName ReleaseStreamResources
 * @Description TODO 释放IO流资源的方式
 * @Author tangxl
 * @create 2023-04-06 17:01
 **/
public class ReleaseStreamResources {
    public static void main(String[] args) {
        // TODO 释放IO流资源的方式
        // 1.使用try-catch-finally语句块
        // 2.使用try-with-resources语句块

        // 1.使用try(){}catch(){}语句块
        InputStream is = null;
        OutputStream os = null;
        try {
             is = new FileInputStream("study-commons/java-file-iostream/src/main/resources/file/a.txt");
             os = new FileOutputStream("study-commons/java-file-iostream/src/main/resources/file/c.txt");
             // 文件字节流操作。。。。
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
             System.out.println("finally");
             // 释放资源
             if (is != null) {
                 try {
                     is.close();
                 } catch (IOException e) {
                     throw new RuntimeException(e);
                 }
             }
             if (os != null) {
                 try {
                     os.close();
                 } catch (IOException e) {
                     throw new RuntimeException(e);
                 }
             }
            }

        // 2.使用try-with-resources语句块
        try (InputStream is1 = new FileInputStream("study-commons/java-file-iostream/src/main/resources/file/a.txt");
             OutputStream os1 = new FileOutputStream("study-commons/java-file-iostream/src/main/resources/file/c.txt")) {
            // 文件字节流操作。。。。
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
